                      <!-- eslint-disable vue/html-self-closing -->
<template>
  <div class="app-container">
    <div class="main">
      <el-form ref="form" :model="form" :rules="rules" label-width="220px" class="demo-form">
        <el-form-item style="width:'220px'" label="姓名" prop="username">
          <el-input v-model="form.username" size="mini" />
        </el-form-item>
        <el-form-item label="工号" prop="workNumber">
          <el-input v-model="form.workNumber" disabled size="mini" />
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-if="mobile" v-model="form.mobile" disabled size="mini" />
          <el-input v-else v-model="form.mobile" size="mini" />
        </el-form-item>
        <el-form-item label="部门" prop="departmentId">
          <!-- v-model="form.departmentId" -->
          <el-cascader
            :value="form.departmentId"
            style="width:100%"
            size="mini"
            :options="options"
            :props="{checkStrictly:true}"
            separator="-"
            @change="changeValue"
          />
        </el-form-item>
        <el-form-item label="聘用形式" prop="formOfEmployment">
          <el-select
            v-model="form.formOfEmployment"
            style="width:100%"
            size="mini"
            placeholder="请选择"
          >
            <el-option label="正式" :value="1" />
            <el-option label="非正式" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="入职时间" required>
          <el-form-item prop="timeOfEntry">
            <el-date-picker
              v-model="form.timeOfEntry"
              type="date"
              style="width: 100%;"
              size="mini"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
        </el-form-item>
        <el-form-item label="转正时间" required>
          <el-form-item prop="correctionTime">
            <el-date-picker
              v-model="form.correctionTime"
              size="mini"
              type="date"
              style="width: 100%;"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
        </el-form-item>
        <el-form-item label="员工头像" required>
          <upload ref="staffPhoto" :staff-photo="staffPhoto"></upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('form')">保存更新</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
let departmentOldArr = []
// 获取部门列表
import { getDepartmentList } from '@/api/department'
// 转换格式
import { dataToTree } from '@/utils/tools'
// 新增
import { addEmployee, getEmployeeInfo, putEmployeeInfo } from '@/api/employee'
// 头像
import upload from '@/components/uploadImage'
// // 引入插件
// var COS = require('cos-js-sdk-v5')
// // SECRETID 和 SECRETKEY 请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
// var cos = new COS({
//   SecretId: 'AKIDCED4lDTXO7mKD2g9ScYJrF4jEZgaLvMg',
//   SecretKey: 'wlT3SbIvXzKYeW8d1JWYQkz3vgbpokdT'
// })
export default {
  name: 'AddEmployee',
  components: {
    upload

  },
  filters: {
    capitalize: function(value) {
      console.log(value)
    }
  },

  props: {},
  data() {
    // 部门校验
    const departmentIdValidator = (rule, value, callback) => {
      if (this.form.departmentId === null) {
        callback(new Error('请选择部门'))
      } else {
        callback()
      }
    }
    // 聘用方式校验
    const formOfEmploymentValidator = (rule, value, callback) => {
      if (this.form.formOfEmployment === null) {
        callback(new Error('请选择聘用形式'))
      } else {
        callback()
      }
    }
    // 入职时间
    const timeOfEntryValidator = (rule, value, callback) => {
      const flag = new Date(this.form.correctionTime) >= new Date(this.form.timeOfEntry)
      if (!flag) {
        callback()
        this.$refs.form.validateField('correctionTime')
      } else if (this.form.timeOfEntry === '') {
        callback(new Error('请选择入职时间'))
      } else {
        callback()
      }
    }
    // 入职时间
    const correctionTimeValidator = (rule, value, callback) => {
      const flag = new Date(this.form.correctionTime) >= new Date(this.form.timeOfEntry)
      if (this.form.correctionTime === '') {
        callback(new Error('请选择聘转正时间'))
      } else if (!flag) {
        if (!this.form.timeOfEntry) {
          callback()
          return
        }
        callback(new Error('转正时间不能小于入职时间'))
      } else {
        callback()
      }
    }
    return {
      form: {
        username: '', // 员工名字
        mobile: '', // 员工手机号
        formOfEmployment: null, // 员工聘用形式
        workNumber: '', // 员工工号
        departmentId: null, // 员工部门id
        timeOfEntry: '', // 员工入职日期
        correctionTime: '', // 员工转正日期
        staffPhoto: '' // 头像信息
      },
      rules: {
        username: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 1, max: 4, message: '姓名为1-4位', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不对', trigger: 'blur' }
        ],
        departmentId: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: departmentIdValidator, trigger: 'blur' }
        ],
        formOfEmployment: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: formOfEmploymentValidator, trigger: 'blur' }
        ],
        timeOfEntry: [
          { validator: timeOfEntryValidator, trigger: 'blur' }
        ],
        correctionTime: [
          { validator: correctionTimeValidator, trigger: 'blur' }
        ],
        workNumber: [

        ]
      },
      options: [], // 部门,
      employeeList: {},
      employeeId: 0,
      mobile: false,
      staffPhoto: ''
    }
  },
  computed: {},
  watch: {},
  created() {
    // 判断是否是查看来的
    if (this.$route.params.id) {
      this.employeeId = this.$route.params.id
      this.getEmployeeInfo()
      this.mobile = true
      this.getDepartmentList()
      return
    }
    this.mobile = false
    this.getDepartmentList()
  },
  mounted() {},
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          // 如果有头像就更改
          // if (this.$refs.staffPhoto.file) {
          //   const file = this.$refs.staffPhoto.file
          //   console.log(file)
          //   const index = file.file.name.lastIndexOf('.')
          //   const ext = file.file.name.slice(index)
          //   // console.log()
          //   this.form.staffPhoto = await this.uploadFile(file, ext)
          //   // await cos.uploadFile({
          //   //   Bucket: 'sjz-hr-1317544063', /* 填写自己的 bucket，必须字段 */
          //   //   Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
          //   //   Key: String(Date.now()) + (Number.parseInt(Math.random() * 10000000)) + (Number.parseInt(Math.random() * 10000000)) + ext, /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
          //   //   Body: file.file, // 上传文件对象
          //   //   SliceSize: 1024 * 1024 * 5, /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
          //   //   onProgress: function(progressData) {
          //   //     console.log(JSON.stringify(progressData))
          //   //   }
          //   // }, (err, data) => {
          //   //   if (err) {
          //   //     console.log('上传失败', err)
          //   //     console.dir(err)
          //   //   } else {
          //   //     console.log('上传成功')
          //   //     this.form.staffPhoto = 'http://' + data.Location
          //   //   }
          //   // })
          // }
          if (this.$route.params.id) {
            // console.log(this.form)
            await putEmployeeInfo(this.form)
            // 提示上传成功
            this.$message.success('员工信息修改成功')
          } else {
            console.log(this.form)
            await addEmployee(this.form)
            // 提示上传成功
            this.$message.success('员工新增成功成功')
          }
          // 跳转会员工页面
          this.$router.push('/employee')
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 获取部门列表
    async getDepartmentList() {
      const { data } = await getDepartmentList()
      // 映射成想要的格式
      departmentOldArr = data
      const arr = data.map(item => {
        return {
          value: item.id, label: item.name, ...item
        }
      })
      this.options = dataToTree(arr)
      // console.log(tree)
      // if (this.$route.params.id) {
      //   this.form.departmentId = this.dataChange([this.form.departmentId])
      // }
    },
    async getEmployeeInfo() {
      // 获取对应id的员工信息
      const { data } = await getEmployeeInfo(this.employeeId)
      this.staffPhoto = data.staffPhoto
      // console.log(data)
      this.form = data
    },
    dataChange(arr) {
      const obj = departmentOldArr.find(item => item.id === arr[0])
      // console.log(obj)
      // console.log(this.options)
      if (!obj) return
      let arr1 = []
      if (obj.pid !== 0) {
        arr1 = this.dataChange([obj.pid, ...arr])
      }
      return [...arr1, obj.id]
    },
    // 部门改变后改变值
    changeValue(list) {
      // 取到数组的最后一次
      if (list.length > 0) {
        this.form.departmentId = list[list.length - 1] // 将最后一位的id取出来
      } else {
        this.form.departmentId = null // 如果长度为0 说明值为空
      }
    },
    uploadSuccess(Location) {
      this.form.staffPhoto = Location
    }
    // uploadFile(file, ext) {
    //   return new Promise((resolve, reject) => {
    //     cos.uploadFile({
    //       Bucket: 'sjz-hr-1317544063',
    //       Region: 'ap-beijing',
    //       Key: String(Date.now()) + (Number.parseInt(Math.random() * 10000000)) + (Number.parseInt(Math.random() * 10000000)) + ext,
    //       Body: file.file,
    //       SliceSize: 1024 * 1024 * 5,
    //       onProgress: function(progressData) {
    //         console.log(JSON.stringify(progressData))
    //       }
    //     }, (err, data) => {
    //       if (err) {
    //         console.log('上传失败', err)
    //         console.dir(err)
    //         reject(err)
    //       } else {
    //         console.log('上传成功')
    //         const location = 'http://' + data.Location
    //         resolve(location)
    //       }
    //     })
    //   })
    // }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 10px;
  .main {
    width: 540px;
    height: 100%;
    margin-top: 20px;
  }
}

// 头像
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
